<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-6-18
 * Time: 上午9:24
 * @author 郑钟良<zzl@ourstu.com>
 */

namespace Addons\Consult;


use Common\Controller\Addon;

class ConsultAddon extends Addon{

    public $info = array(
        'name' => 'Consult',
        'title' => '购买咨询',
        'description' => '适用于微店、云市场、积分商城，用于购买咨询',
        'status' => 1,
        'author' => '嘉兴想天科技有限公司-zzl(郑钟良)',
        'version' => '2.0.0',
    );

    public $admin_list = array(
        '' => '',
    );

    public function install()
    {
        $prefix=C("DB_PREFIX");
        D()->execute("DROP TABLE IF EXISTS `{$prefix}consult`");
        $sql=<<<SQL
CREATE TABLE IF NOT EXISTS `{$prefix}consult` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `uid` int(11) NOT NULL,
  `type_id` int(11) NOT NULL COMMENT '类型id',
  `content` text NOT NULL COMMENT '咨询内容',
  `answer` text NOT NULL COMMENT '回答内容',
  `answer_uid` int(11) NOT NULL COMMENT '回答者uid',
  `goods_uid` int(11) NOT NULL COMMENT '商品(咨询对象)拥有者uid',
  `status` tinyint(4) NOT NULL,
  `update_time` int(11) NOT NULL,
  `create_time` int(11) NOT NULL,
  `table_name` varchar(25) NOT NULL COMMENT '咨询对象表名',
  `row_id` int(11) NOT NULL COMMENT '咨询对象行号',
  `from_url` varchar(100) NOT NULL COMMENT '商品详情页url',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='咨询数据表' AUTO_INCREMENT=1 ;
SQL;
        D()->execute($sql);
        D()->execute("DROP TABLE IF EXISTS `{$prefix}consult_category`");
        $sql=<<<SQL
CREATE TABLE IF NOT EXISTS `{$prefix}consult_category` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(25) NOT NULL,
  `status` tinyint(4) NOT NULL,
  `tip` varchar(300) NOT NULL,
  `use_space` varchar(200) NOT NULL,
  `sort` int(6) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT='咨询分类' AUTO_INCREMENT=1 ;
SQL;
        D()->execute($sql);

        $sql=<<<SQL
INSERT INTO `{$prefix}hooks` (`name`, `description`, `type`, `update_time`, `addons`) VALUES
('consult', '购买咨询', 1, 1434698849, 'Consult');
SQL;
        D()->execute($sql);

        $sql=<<<SQL
INSERT INTO `{$prefix}action` ( `name`, `title`, `remark`, `rule`, `log`, `type`, `status`, `update_time`, `module`) VALUES
( 'consult_ask', '发表咨询', '用户对商品进行咨询', '', '', 2, 1, 1435130656, 'Core'),
( 'consult_answer', '回复咨询', '店长或管理员回复商品咨询', '', '', 2, 1, 1435130934, 'Core'),
('consult_delete', '删除咨询', '用户删除咨询', '', '', 2, 1, 1435210065, 'Core');
SQL;
        D()->execute($sql);

        $sql=<<<SQL
INSERT INTO `{$prefix}action_limit` ( `title`, `name`, `frequency`, `time_number`, `time_unit`, `punish`, `if_message`, `message_content`, `action_list`, `status`, `create_time`, `module`) VALUES
( 'consult_ask', '发表咨询', 1, 1, 'minute', 'warning', 0, '操作太频繁！1分钟后再试~', '[consult_ask]', 1, 0, 'Core');
SQL;
        D()->execute($sql);

        $sql=<<<SQL
INSERT INTO `{$prefix}auth_rule` ( `module`, `type`, `name`, `title`, `status`, `condition`) VALUES
('Core', 1, 'Addons/Consult/Consult/answer', '回复咨询权限(管理)', 1, ''),
('Core', 1, 'Addons/Consult/Consult/ask', '发表咨询权限', 1, ''),
('Core', 1, 'Addons/Consult/Consult/delete', '删除咨询（管理）', 1, '');
SQL;
        D()->execute($sql);

        return true;
    }

    public function uninstall()
    {
        $prefix = C("DB_PREFIX");
        D()->execute("DROP TABLE IF EXISTS `{$prefix}consult`");
        D()->execute("DROP TABLE IF EXISTS `{$prefix}consult_category`");
        D()->execute("DELETE FROM `{$prefix}hooks` WHERE `name`='consult'");
        D()->execute("DELETE FROM `{$prefix}action` WHERE `name` in ('consult_ask','consult_answer','consult_delete')");
        D()->execute("DELETE FROM `{$prefix}action_limit` WHERE `title`='consult_ask'");
        D()->execute("DELETE FROM `{$prefix}auth_rule` WHERE `name` in ('Addons/Consult/Consult/answer','Addons/Consult/Consult/ask','Addons/Consult/Consult/delete')");
        return true;
    }

    public function consult($data)
    {
        $this->_checkUseSpace($data);
        $this->_assignCategory($data);

        $consult_info=array('table_name'=>$data['table_name'],'row_id'=>$data['row_id'],'limit'=>$data['limit'],'goods_uid'=>$data['goods_uid'],'from_url'=>$data['from_url']);
        $this->assign('consult_info',$consult_info);

        $map['table_name']=$data['table_name'];
        $map['row_id']=$data['row_id'];
        $map['status']=1;
        $consultModel=D('Addons://Consult/Consult');
        list($list,$totalCount)=$consultModel->getList($map,'create_time desc',$data['limit']);
        $this->assign('consult_list',$list);
        $this->assign('consult_totalCount',$totalCount);

        if($totalCount>$data['limit']){
            $this->assign('show_more',1);
        }
        $list_content=$this->fetch(T('Addons://Consult@Consult/consult_list'));

        $this->assign('list_content',$list_content);
        $this->assign('consult_tip',$this->_getAddonsConfig('tip'));
        $this->display(T('Addons://Consult@Consult/show'));
    }

    private function _assignCategory($data)
    {
        $map_category['use_space']=array('like',array('%['.$data['table_name'].']%',''));
        $map_category['status']=1;
        $list=D('Addons://Consult/ConsultCategory')->getList($map_category);
        $this->assign('consult_category_list',$list);
    }

    private function _getAddonsConfig($name='')
    {
        $config=S('CONSULT_ADDONS_CONFIG');
        if(!$config){
            $map['name']    =   "Consult";
            $map['status']  =   1;
            $config  =   M('Addons')->where($map)->getField('config');
            $config=json_decode($config,true);

            $use_space = str_replace("\r", '', $config['use_space']);
            $use_space = explode("\n", $use_space);
            $config['use_space']=array();
            foreach ($use_space as &$v) {
                $temp = explode(':', $v);
                $config['use_space'][$temp[0]] = $temp[1];
            }

            S('CONSULT_ADDONS_CONFIG',$config);
        }
        if($name!=''){
            return $config[$name];
        }
        return $config;
    }

    private function _checkUseSpace($data)
    {
        $config=$this->_getAddonsConfig();
        if(!isset($config['use_space'][$data['table_name']])){
            $config['use_space'][$data['table_name']]=$data['name'];
            foreach ($config['use_space'] as $key=>&$v) {
                $temp=array($key,$v);
                $temp = implode(':', $temp);
                $v = $temp;
            }
            $config['use_space'] = implode("\n", $config['use_space']);
            $config=json_encode($config,true);
            $map['name']    =   "Consult";
            $map['status']  =   1;
            $config  =   M('Addons')->where($map)->setField('config',$config);
            S('CONSULT_ADDONS_CONFIG',$config);
        }
        return true;
    }

} 